package com.zxq.common.utils.response;


import com.zxq.common.utils.DateUtil;
import com.zxq.common.utils.exception.ErrorCode;
import com.zxq.common.utils.exception.IErrorCode;

import java.io.Serializable;

public class BaseResponse<T> implements Serializable {

    private static final long serialVersionUID = -2465140747749709626L;
    private Long timestamp = System.currentTimeMillis();

    private int code;
    private String msg;
    private T data;

    private static <T> BaseResponse<T> build(int code, String msg, T data) {
        BaseResponse<T> response = new BaseResponse<>();
        response.setData(data);
        response.setCode(code);
        response.setMsg(msg);
        return response;
    }


    public static <T> BaseResponse<T> buildSuccess() {
        return build(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMessage(), null);
    }

    public static <T> BaseResponse<T> buildSuccess(String msg) {
        return build(ErrorCode.SUCCESS.getCode(), msg, null);
    }

    public static <T> BaseResponse<T> buildSuccess(T data) {
        return build(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMessage(), data);
    }


    public static <T> BaseResponse<T> buildFailure() {
        return build(ErrorCode.BUSINESS_ERROR.getCode(), ErrorCode.BUSINESS_ERROR.getMessage(), null);
    }

    public static <T> BaseResponse<T> buildFailure(String errorMsg) {
        return build(ErrorCode.BUSINESS_ERROR.getCode(), errorMsg, null);
    }

    public static <T> BaseResponse<T> buildFailure(IErrorCode baseResult) {
        return build(baseResult.getCode().getCode(), baseResult.getCode().getMessage(), null);
    }

    public static <T> BaseResponse<T> buildFailure(Integer errorCode, String errorMsg) {
        return build(errorCode, errorMsg, null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    @Override
    public String toString() {
        return "ApiDataResult{" +
               "  code=" + code +
               ", msg=" + msg +
               ", data=" + data +
               ", timestamp=" + DateUtil.ymdHms(timestamp) +
               '}';
    }
}
